package org.bite.lesson13;

import java.util.concurrent.TimeUnit;

/**
 * 解决刚刚的死锁
 * 规定一下获取锁的顺序
 */
public class Demo1303 {
    public static void main(String[] args) {
        //所有线程都先拿locker1再拿locker2
        Object locker1 = new Object();
        Object locker2 = new Object();

        Thread t1 = new Thread(()->{
            System.out.println("t1申请locker1……");
            synchronized(locker1){
                System.out.println("t1获取到了locker1");
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }

                synchronized (locker2){
                    System.out.println("t1获取到了locker2");
                }
            }
        });

        Thread t2 = new Thread(()->{
            System.out.println("t2申请locker1……");
            synchronized(locker1){
                System.out.println("t2获取到了locker1");
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }

                synchronized (locker2){
                    System.out.println("t2获取到了locker2");
                }
            }
        });

        t1.start();
        t2.start();
    }
}
